﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Drawing;

namespace InductBase.Extra
{
	public class RasterFont
	{

		string name;

		public int bw_chars;
		public int bw_rows;
		public int bw_space;

		Bitmap bmp;

		public class Gliph
		{
			public char ch;
			public Rec area;
		};

		public Dictionary<char, Gliph> gliphs;

		public void LoadIndieFont(string path)
		{
			bw_chars = 0;
			bw_space = 5;

			bmp = new Bitmap(path + ".png");

			gliphs = new Dictionary<char, Gliph>();

			XmlDocument doc = new XmlDocument();
			doc.Load(path+".xml");

			//===========
			XmlNode node = doc.DocumentElement;//font
			int numchar = Int32.Parse(node.Attributes["num_characters"].Value);

			var XChars = node.ChildNodes;//chars

			for (int i = 0; i < XChars.Count; i++)
			{
				Gliph g = new Gliph();
				g.area = new Rec();

				int charval = Int32.Parse(XChars[i].Attributes["id"].Value);
				g.ch = (char) charval;

				int x =Int32.Parse(XChars[i].Attributes["x"].Value);
				int y =Int32.Parse(XChars[i].Attributes["y"].Value);
				int width =Int32.Parse(XChars[i].Attributes["width"].Value);
				int height =Int32.Parse(XChars[i].Attributes["height"].Value);

				g.area.Min = new Vec2(x, y);
				g.area.Size = new Vec2(width, height);

				if(bw_rows < height) bw_rows = height;

				gliphs[g.ch] = g;
			}
		}

		public void Draw(Graphics g, int x, int y, string text)
		{
			int cx, cy;
			cx = x;
			cy = y;

			for (int i = 0; i < text.Length; i++)
			{
				if (text[i] == '\n') { cy += bw_rows; cx = x; continue; }
				if (text[i] == ' ') { cx += bw_space; continue; }

				Gliph gl;
				try
				{
					gl = gliphs[text[i]];
				}
				catch { continue; }

				g.DrawImage(
					bmp,
					new Rectangle(cx, cy, (int)gl.area.Size.X, (int)gl.area.Size.Y),
					new Rectangle((int)gl.area.Min.X, (int)gl.area.Min.Y, (int)gl.area.Size.X, (int)gl.area.Size.Y),
					GraphicsUnit.Pixel
					);

				cx += (int)gl.area.Size.X;
			}
		}

		public Vec2 GetSize(string text)
		{
			int cx, cy, rx;
			cx = 0;
			cy = 0;
			rx = 0;

			for (int i = 0; i < text.Length; i++)
			{
				if (text[i] == '\n') { cy += bw_rows; cx = 0; continue; }
				if (text[i] == ' ') { cx += bw_space; continue; }

				Gliph gl;

				try
				{
					gl = gliphs[text[i]];
				}
				catch { continue; }

				cx += (int)gl.area.Size.X;
				if (cx > rx) rx = cx;
			}

			cy += bw_rows;
			return new Vec2(rx, cy);
		}
		
	}
}
